<template>
  <div :class="closeLabel === '关闭' ? 'one-bill-wrap box-height' : 'one-bill-wrap'">
    <div :class="closeLabel === '关闭' ? 'container w1200':'container'">
      <details-head v-model="status"
                    :title="`合单报价`"
                    :multiple="true"
                    :custom-list="btnGroup"
                    :close-label="closeLabel"
                    close-flag
                    :loading="loading"
                    :show-print="isCombineQuoteFee"
                    :print-router="printPath"
                    :print-query="{ combineId: value.combineId }"
                    @change="handleSubmit"
                    @close="handelClose" />
      <desc-list v-if="value.combineId"
                 :waybill-details="combineDetails" />
      <icon-svg v-if="matchId"
                class-name="stampSty"
                icon-name="a-ziyuan4" />
      <layer title="合单子单">
        <child-list :table-data="childListData" />
      </layer>
      <layer title="费用信息">
        <TransportQuote v-if="quotationColumn"
                        ref="transportQuote"
                        :is-one-bill="true"
                        :disabled="transportDisabled"
                        :quotation-column.sync="quotationColumn"
                        :data-list="quotationColumnData"
                        :status="status"
                        :waybill-quote-bargain="waybillQuoteBargain"
                        :match-id="matchId"
                        :match-column="combineFeeColumn"
                        :match-data="combineMatchData"
                        :surcharge-fees="matchSurchargeData"
                        @returnData="returnData"
                        @onTotal="handleQuoteTotal" />
        <Bargain v-show="!isCombineQuoteFee && computedDriver"
                 ref="bargainRef"
                 class="mb20"
                 :disabled="addDisabled"
                 :data-list="addCostList"
                 :status="status"
                 :surcharge="surcharge"
                 :fee-type-arr="feeTypeArr"
                 :add-action-disabled="addActionDisabled"
                 :waybill-quote-bargain="waybillQuoteBargain"
                 @onTotal="handleQuoteTotal" />
        <div v-if="!isCombineQuoteFee"
             class="fontSty1">
          {{computedDriver ? "报价费用+补充费用合计(含税费):" : "报价费用(含税费):" }}
          <span class="fontSty2">{{ totalFee }}</span>
        </div>
        <SurchargeFee v-if="isCombineQuoteFee"
                      class="mb20"
                      :data-list="matchSurchargeData" />
        <pay-type ref="payType"
                  :class="isCombineQuoteFee ? 'mt25' : ''"
                  is-one-bill
                  :disabled="payDisabled"
                  :status="status"
                  :arrive-pay-fee-disabled="arrivePayFeeFlag"
                  :collection-fee-disabled="collectionFeeFlag"
                  :prepay-fee-disabled="prepayFeeFlag"
                  :waybill-price="combineDetails && combineDetails.price"
                  :data-list="payList"
                  :waybill-quote-bargain="waybillQuoteBargain" />
        <div v-show="computedDriver"
             class="mt25">
          <el-input v-if="!descDisabled"
                    v-model="remarks"
                    type="textarea"
                    :rows="4"
                    maxlength="200"
                    show-word-limit
                    placeholder="请输入备注说明" />
          <p v-else
             class="remark wrap">{{isCombineQuoteFee ? '报价备注：': '备注：'}}{{ remarks }}</p>
        </div>
      </layer>
      <layer v-show="isTrack"
             title="跟踪信息">
        <Information :value="track" />
      </layer>
      <Reject v-if="visible"
              :id="value.quotationId"
              :label="'reason'"
              :api="api.refuse"
              :visible.sync="visible"
              id-name="quotationId"
              @back="handelClose" />
    </div>
  </div>
</template>

<script>
import DetailsHead from "@components/detailsHead/Header.vue";
import Layer from "@/components/detailsLayer/Layer";
import DescList from "../oneBill/components/DescList";
import ChildList from "../oneBill/components/ChildList.vue";
import TransportQuote from "../transport/components/TransportQuote.vue";
import Bargain from '../transport/components/Bargain.vue'
import PayType from "../transport/components/PayType.vue";
import SurchargeFee from "../transport/components/SurchargeFee.vue";
import Reject from "../transport/components/Reject.vue";
import Information from "@/components/track/Information.vue";
import completeData from "@/libs/conversion.js";
import { onebill, quotation, track } from "@/api/index";
import { returnThousandDigit } from "@/libs/util.js";
import { COMBINE_SOLO_QUOTATION_COLUMN, COMBINE_QUOTATION_COLUMN, STATUS_LABEL } from "../transport/quotation.mixin";
import { mapState } from "vuex";

export default {
  name: "CombineQuotation",
  components: {
    DetailsHead,
    Layer,
    DescList,
    ChildList,
    TransportQuote,
    Bargain,
    PayType,
    SurchargeFee,
    Reject,
    Information
  },
  data () {
    return {
      api: quotation,
      loading: false,
      visible: false,
      combineDetails: {},
      childListData: [],
      matchId: null,
      matchVisible: false,
      carrierExtraType: null, // 是否是个体司机,
      quoteDetail: {},      // 合单报价详情
      validQuoteDetail: null, // 合单有效报价详情
      combineFeeColumnData: [], // 合单费用-费用
      matchSurchargeData: [],  // 合单匹配合约-补充费用
      feeTypeArr: [],  // 补充费用-已存在费用的费用项
      quoteTotal: 0, // 合单费用合计
      bargainTotal: 0, //补充费用合计
      bargainSwitch: false,  // 议价开关
      remarks: null, // 备注
      track: [], // 跟踪信息
      isTrack: false, // 跟踪信息标题显示
    };
  },
  computed: {
    ...mapState({
      tenantInfo: (state) => state.tenant.tenantInfo
    }),
    value () {
      return this.$route.query;
    },
    status () {
      if (this.value?.status) {
        return this.value?.status.toString();
      }
      if (this.value?.status === 0) {
        return '0';
      }
    },
    surcharge () {
      return this.quoteDetail?.surcharge || (this.value?.surcharge?.toString() === 'true');
    },
    closeLabel () {
      return this.isCombineQuoteFee || ["32", "14"].includes(this.status) ? '关闭' : '返回';
    },
    // 报价-议价
    waybillQuoteBargain () {
      const { name } = this.$route
      return name === 'combineQuoteBargain' ? true : this.bargainSwitch;
    },
    /* 是否为合单费用途径进入 */
    isCombineQuoteFee () {
      const { name } = this.$route
      return name === 'combineQuoteFee';
    },
    /** 合单报价禁用编辑 */
    transportDisabled () {
      let transportStatus = ["1", "2", "18", "32", "14"];
      if (transportStatus.includes(this.status)
        || (this.status === "3" && this.surcharge)
        || (['8', '11'].includes(this.status) && !this.waybillQuoteBargain)
        || (this.waybillQuoteBargain && this.surcharge)
        || this.isCombineQuoteFee
      ) {
        return true;
      }
      return false;
    },
    /** 补充费用报价禁用编辑 */
    addDisabled () {
      let addStatus = ["1", "6", "18", "32", "14"];
      if (addStatus.includes(this.status)
        || (['8', '11'].includes(this.status) && !this.waybillQuoteBargain)
      ) {
        return true;
      }
      return false;
    },
    /** 付款方式禁用编辑 */
    payDisabled () {
      // 1待审核 8议价 11审核报价 32关闭
      let payStatus = ["1", "18", "32", "14"];
      if (payStatus.includes(this.status)
        || (['8', '11'].includes(this.status) && !this.waybillQuoteBargain)
        || this.isCombineQuoteFee
      ) {
        return true;
      }
      return false;
    },
    /** 备注禁用编辑 */
    descDisabled () {
      // 1待审核 2补充报价 8议价 11审核报价 32 14 关闭
      let descStatus = ["1", "2", "8", "11", "18", "32", "14"];
      if (descStatus.includes(this.status) || this.waybillQuoteBargain || this.isCombineQuoteFee) {
        return true;
      }
      return false;
    },
    /** 补充费用新增操作禁用 */
    addActionDisabled () {
      // 审核报价-议价、议价审核方 disabled：true
      if (this.status === '11' && (this.waybillQuoteBargain || this.bargainSwitch)
        || (!this.initiator && (this.waybillQuoteBargain || this.bargainSwitch))
      ) {
        return true;
      }
      return false;
    },
    /** 合单报价列 */
    combineQuotaionColumn () {
      let column = [];
      column = this.carrierExtraType ? COMBINE_SOLO_QUOTATION_COLUMN : COMBINE_QUOTATION_COLUMN;
      column.forEach(ele => {
        if (ele.name != "quoteTotal") {
          ele.type = this.transportDisabled ? "text" : "input"
        }
      });
      if (!this.carrierExtraType && this.quoteDetail?.minimumFee) {
        column.splice(column.length - 1, 0, {
          label: "最低费用",
          name: "minimumFee",
          type: this.transportDisabled ? "text" : "input"
        });
      }

      return column || [];
    },
    /** 合单报价费用 */
    priceList () {
      let priceArr = [];
      if (this.value?.quotationId && this.quoteDetail) {
        priceArr = [{
          transport: this.quoteDetail?.transportFee || 0,
          pick: this.quoteDetail?.pickFee || 0, //提货费
          deliver: this.quoteDetail?.deliverFee || 0, //送货费
          load: this.quoteDetail?.loadFee || 0, //装货费
          unload: this.quoteDetail?.unloadFee || 0, //卸货费
          insure: this.quoteDetail?.insureFee || 0,  //保险费
          tax: this.quoteDetail?.taxFee || 0, //税费
          minimumFee: this.quoteDetail?.minimumFee || 0 //最低费用
        }];

        let priceTotal = 0; //合单费用合计
        if (this.quoteDetail?.minimumFee) {
          priceTotal = this.quoteDetail.minimumFee + priceArr[0].tax + priceArr[0].insure
        } else {
          // 计算合单费用总和
          for (let key in priceArr[0]) {
            priceTotal += priceArr[0][key];
          }
        }
        priceArr[0].quoteTotal = Number(priceTotal.toFixed(2));
        this.quoteTotal = Number(priceTotal.toFixed(2));
        // 议价-议价前费用显示
        if (this.status === '8' || this.waybillQuoteBargain) {
          priceArr[0].transportFeeBefore = this.quoteDetail?.transportFeeBefore;
          priceArr[0].pickFeeBefore = this.quoteDetail?.pickFeeBefore;
          priceArr[0].deliverFeeBefore = this.quoteDetail?.deliverFeeBefore;
          priceArr[0].loadFeeBefore = this.quoteDetail?.loadFeeBefore;
          priceArr[0].unloadFeeBefore = this.quoteDetail?.unloadFeeBefore;
          priceArr[0].insureFeeBefore = this.quoteDetail?.insureFeeBefore;
          priceArr[0].taxFeeBefore = this.quoteDetail?.taxFeeBefore;
        }
      }
      return priceArr;
    },
    /** 补充费用 */
    addCostList () {
      let bargainTotal = 0;     //附加费用合计
      let surchargeData = [];   // 附加费用列表数据源
      let surchargeFees = this.quoteDetail?.surchargeFees || [];
      if (this.surcharge) {
        if (this.status === "2") {
          surchargeData = surchargeFees;
        }
        if ((["8"].includes(this.status) || (this.waybillQuoteBargain && this.surcharge)) && surchargeFees?.length > 0) {
          this.quoteDetail.surchargeFees.map((item) => {
            item.typeDisabled = true;
          });
        }

        let bargainLabel = this.waybillQuoteBargain && this.surcharge ? '议价' : null;
        let bargainLabelOption = {
          title: bargainLabel || STATUS_LABEL[this.status],
          typeName: bargainLabel || STATUS_LABEL[this.status],
          typeDisabled: true
        };
        // 补充报价-补充报价/被拒绝待审核、审核报价、审核报价-议价的状态，补充费用数据源
        if (
          (this.status === "1" && this.quoteDetail.status != 8)
          || (this.status === "11" && this.quoteDetail.status != 8)
          || (this.status === "11" && this.waybillQuoteBargain && this.surcharge && this.quoteDetail.status != 8)
        ) {
          surchargeData = surchargeFees?.length > 0
            ? [...this.quoteDetail.surchargeFees, { ...bargainLabelOption }]
            : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.auditingFees && this.quoteDetail?.auditingFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.auditingFees]
              : surchargeData;
        }
        // 补充报价-议价待审核、补充报价-议价的状态，补充费用数据源
        if (
          (this.status === "1" && this.quoteDetail.status === 8) ||
          this.status === "8" || this.status === '18' ||
          (this.status === '8' && this.waybillQuoteBargain && this.surcharge) ||
          (this.status === "11" && this.quoteDetail.status === 8) ||
          (this.status === '11' && this.waybillQuoteBargain && this.surcharge && this.quoteDetail.status === 8)
        ) {
          surchargeData = surchargeFees?.length > 0
            ? [...this.quoteDetail.surchargeFees, { ...bargainLabelOption }]
            : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.bargainFees && this.quoteDetail?.bargainFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.bargainFees]
              : surchargeData;
        }
        // 补充报价被拒绝的状态，补充费用数据源
        if (this.status === "3") {
          let list = [];
          if (surchargeFees?.length > 0) {
            list = surchargeFees.map((item) => {
              item.typeDisabled = true;
              return item;
            });
          }
          surchargeData =
            list.length > 0
              ? [...list, { ...bargainLabelOption }]
              : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.rejectedFees && this.quoteDetail?.rejectedFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.rejectedFees]
              : surchargeData;
        }
        // 已关闭
        if (["32", "14"].includes(this.status)) {
          let list = [];
          if (surchargeFees?.length > 0) {
            list = surchargeFees.map((item) => {
              item.typeDisabled = true;
              return item;
            });
          }
          surchargeData =
            list.length > 0
              ? [...list, { ...bargainLabelOption }]
              : [{ ...bargainLabelOption }];
          surchargeData =
            this.quoteDetail?.closedFees && this.quoteDetail?.closedFees?.length > 0
              ? [...surchargeData, ...this.quoteDetail.closedFees]
              : surchargeData;
        }
      } else {
        surchargeData = surchargeFees.length ? surchargeFees : this.quoteDetail?.bargainFees;
      }
      //附加费用相加
      surchargeData && surchargeData.forEach((element) => {
        if (["2"].includes(this.status) && !element.add) element.typeDisabled = true;
        if (element.type) element.disabled = true;
        bargainTotal += Number(element.money) || 0;
      });
      // 总补充费用
      this.bargainTotal = bargainTotal;
      this.feeTypeArr = surchargeData && surchargeData.map((item) => {
        if (!item.typeDisabled) {
          return item.type;
        }
      });

      return surchargeData || [];
    },
    /** 预付费用 */
    payList () {
      let payArr = []
      let data = this.isCombineQuoteFee ? this.validQuoteDetail : this.quoteDetail;
      if ((this.value?.quotationId && this.quoteDetail) || this.validQuoteDetail) {
        payArr = [{
          arrivePayFee: data?.arrivePayFee || 0, //货到付款
          prepayFee: data?.prepayFee || 0 //预付款
        }]
      }
      // 议价-议价前费用显示
      if (!this.isCombineQuoteFee && (this.status === '8' || this.waybillQuoteBargain)) {
        payArr[0].arrivePayFeeBefore = data?.arrivePayFeeBefore;
        payArr[0].prepayFeeBefore = data?.prepayFeeBefore;
      }
      return payArr || [];
    },
    /** 运单+补充费用的合计 */
    totalFee () {
      let num = returnThousandDigit(
        Number(this.quoteTotal) + Number(this.bargainTotal),
        2
      );
      return num || 0
    },
    /** 合单费用-费用列 */
    combineFeeColumn () {
      let column = [
        { label: "合单运费", name: "wholeFee", type: 'text' },
        { label: "装货费", name: "loadFee", type: 'text' },
        { label: "卸货费", name: "unloadFee", type: 'text' }
      ]
      // carrierExtraType 字段为1是个体司机---为0不是个体司机
      if (!this.carrierExtraType) {
        column.push(
          { label: "提货费", name: "pickFee", type: 'text' },
          { label: "送货费", name: "deliverFee", type: 'text' },
          { label: "保险费", name: "insureFee", type: 'text' },
          { label: "税费", name: "taxFee", type: 'text' },
        )
      } else {
        column.push({ label: "保险费", name: "insureFee", type: 'text' })
      }
      if (this.combineDetails?.price?.minCost) {
        column.push(
          { label: "最低费用", name: "minCost", type: 'text' },
        )
      }
      column.push(
        { label: "补充费用", name: "surchargeFee", type: 'text' },
        { label: "总费用", name: "totalFee", type: 'total' }
      )

      return column;
    },
    /** 合单的第一个子单 */
    fristChildWaybill () {
      return this.combineDetails.waybills && this.combineDetails.waybills[0]
    },
    arrivePayFeeFlag () {
      return this.fristChildWaybill?.finance?.arrivePayFeeFlag;
    },
    collectionFeeFlag () {
      return this.fristChildWaybill?.finance?.collectionFeeFlag;
    },
    prepayFeeFlag () {
      return this.fristChildWaybill?.finance?.prepayFeeFlag;
    },
    // 租户配置打印路由
    printTemplate () {
      return this.tenantInfo?.config?.printTemplate || [];
    },
    // 有效打印路由
    effectivePaths () {
      return ['CombineFeePrint'];
    },
    // 打印路由
    printPath () {
      const cstPrintName = 'customerCombineFeeTemplate';
      const carrPrintName = 'carrierCombineFeeTemplate';
      let path = null;
      let printName = this.fristChildWaybill?.waybillType === 10 ? cstPrintName : carrPrintName;
      this.printTemplate?.length && this.printTemplate.some((o) =>
        (path = printName === o.name ? o.value.split(";") : null)
      );
      if (path && path.length) {
        return this.effectivePaths.includes(path[0]) ? path[0] : 'CombineFeePrint'
      }
      return 'CombineFeePrint';
    },
    btnGroup () {
      // 待报价、草稿、按单报价-被拒绝
      let group = [];
      if (!this.isCombineQuoteFee) {
        group = [{ label: "发送", status: 10 },
        { label: "保存", status: 20 }]
      }
      // 草稿、被拒绝，可关闭报价单
      if (["0", "3"].includes(this.status)) {
        group.push({ label: "关闭", status: 110 })
      }
      // 待审核，可撤回报价单
      if (this.status === "1") {
        group = [{ label: "撤回", status: 40 }];
      }
      // 补充报价-被拒绝
      if (this.status === "3" && this.surcharge) {
        group = [
          { label: "发送", status: 100 }, //发送补充议价
          { label: "关闭", status: 110 }
        ];
      }
      // 议价、补充报价-议价
      if (this.waybillQuoteBargain) {
        group = [
          { label: "发送", status: 50 } //发送议价
        ];
      }
      // 议价-合同编号进入
      if (this.status === "8" && !this.waybillQuoteBargain) {
        group = [
          { label: "同意", status: 30 }, //同意报价
          { label: "议价", status: 70 } //跳转议价
        ];
      }
      // 审核报价-合同编号进入
      if (this.status === "11" && !this.waybillQuoteBargain) {
        group = [
          { label: "同意", status: 30 }, //同意报价
          { label: "拒绝", status: 60 },
          { label: "议价", status: 70 } //70跳转议价
        ];
      }
      // 补充报价
      if (this.status === "2") {
        group = [
          { label: "发送", status: 90 } //发送补充报价
        ];
      }
      // 议价中、已关闭
      if (["18", "32", '14'].includes(this.status)) {
        group = [];
      }
      return group;
    },
    computedDriver () {
      /** 个体司机按单报价 不要有补充费用、备注、代收货款 */
      /* 不是个体司机报价 或 是个体司机报价，并进入到补充报价环节 */
      let flag = !this.carrierExtraType || (this.carrierExtraType && (this.surcharge || this.quoteDetail?.status === 2) || (this.carrierExtraType && this.isCombineQuoteFee));
      return flag;
    },
    /** 合单报价列 */
    quotationColumn () {
      return this.isCombineQuoteFee ? this.combineFeeColumn : this.combineQuotaionColumn;
    },
    quotationColumnData () {
      return this.isCombineQuoteFee ? this.combineFeeColumnData : this.priceList;
    },
    /** 合单匹配合约-合单费用 */
    combineMatchData () {
      let data = this.isCombineQuoteFee ? this.validQuoteDetail : this.quoteDetail;

      this.matchSurchargeData = data?.surchargeFees || [];
      let matchSurchargeTotal = 0;
      this.matchSurchargeData.forEach((element) => {
        matchSurchargeTotal += element.money || 0;
      });
      // 合单费用
      let combineMatchTotal = 0;
      let dataArr = [{
        wholeFee: data?.transportFee || 0, //合单费用
        pickFee: data?.pickFee || 0, //提货费
        deliverFee: data?.deliverFee || 0, //送货费
        loadFee: data?.loadFee || 0, //装货费
        unloadFee: data?.unloadFee || 0, //卸货费
        insureFee: data?.insureFee || 0, //保险费
        taxFee: data?.taxFee || 0, // 税费
        minCost: data?.minimumFee || 0 //最低费用
      }];
      if (data?.minimumFee) {
        combineMatchTotal = data.minimumFee + data?.taxFee || 0 + data?.insureFee || 0;
      } else {
        for (let key in dataArr[0]) {
          combineMatchTotal += dataArr[0][key];
        }
      }
      dataArr[0].quoteTotal = combineMatchTotal;
      dataArr[0].surchargeFee = matchSurchargeTotal;
      dataArr[0].totalFee = returnThousandDigit(combineMatchTotal + matchSurchargeTotal, 2)
      return dataArr;
    },
    // true:发起方、false:审核方
    initiator () {
      return this.quoteDetail?.originator;
    },
  },
  created () {
    this.getCombineDetail();
    this.trackInformation();
    if (this.value?.quotationId) {
      this.getQuotation();
    }
  },
  methods: {
    thousandDigit (value, digit) {
      return returnThousandDigit(value, digit)
    },
    // 获取合单信息
    async getCombineDetail () {
      let { data } = await onebill.getCombineDetail(this.value.combineId);
      let { waybills } = data;
      this.combineDetails = data;
      this.combineDetails.orderSubQuantity = waybills?.length;
      this.childListData = completeData.redirect(waybills);
      this.carrierExtraType = data.carrier?.carrierExtraType;
      this.combineFeeColumnData = data?.price ? [{ ...data?.price }] : [{}];
      if (data?.price?.quotationStatus && this.isCombineQuoteFee) {
        this.getValidQuote();
      }
    },
    // 获取有效报价
    async getValidQuote () {
      let { data } = await quotation.getValidCombineQuotation(this.value.combineId);
      if (data) {
        this.validQuoteDetail = data;
        this.matchId = data?.matchId;
        this.remarks = data?.remarks;
      }
    },
    /* 查询报价详情 */
    async getQuotation () {
      let { data } = await quotation.getQuotation(this.value.quotationId);
      this.quoteDetail = data;
      this.matchId = data?.matchId;
      this.remarks = data?.remarks;
    },
    /** 报价前置效验 */
    async validateQuotation ({ val, message, postData }) {
      let { data } = await quotation.validateQuote(this.value.subjectId);
      // 校验是否已发送报价单
      if (!data.validate) {
        if (data.flag === 1) {
          this.$confirm("已向您发起了报价，是否去审核?", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.status = '11';
            this.value.quotationId = data.quotationId;
          });
        } else if (data.flag === 2) {
          this.$confirm("报价单正在处理中，不能重复报价", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.handelClose();
          });
        }
      } else {
        this.confirmAction(val, message, postData);
      }
    },
    returnData (val) {
      this.priceList = [{ ...val }];
    },
    // 合单报价费用合计
    handleQuoteTotal (type, val) {
      this.quoteTotal = type === 1 ? val : this.quoteTotal;
      this.bargainTotal = type === 2 ? val : this.bargainTotal;
    },
    // 触发事件
    handleSubmit (val) {
      if (val === 40) {
        return this.confirmAction(val, "确认撤回报价单");
      }
      if (val === 30) {
        return this.confirmAction(val, "是否确认同意报价单");
      }
      if (val === 60) {
        this.visible = true;
        return
      }
      if (val === 70) {
        this.bargainSwitch = true;
        return
      }
      if (val === 110) {
        return this.$confirm("确认关闭报价单？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.closeQuotation();
        });
      }
      let waybillCost = this.$refs.transportQuote.tableData[0];
      if (Object.keys(waybillCost).length === 0) {
        return this.$message.warning("请至少填写一项报价费用");
      }
      let payTypeData = this.$refs.payType.tableData;
      let num = 0;
      for (let key in payTypeData[0]) {
        if (['arrivePayFee', 'prepayFee'].includes(key)) {
          num += Number(payTypeData[0][key]);
        }
      }
      if (num > (Number(this.quoteTotal) + Number(this.bargainTotal))) {
        this.$confirm("预付款,货到付款的总额大于总金额, 是否继续?", {
          title: "提示",
          type: "warning"
        })
          .then(() => {
            this.handleSave(val);
          })
      } else {
        this.handleSave(val);
      }
    },
    // 二次确认框
    confirmAction (val, message, postData) {
      this.$confirm(
        `${this.waybillQuoteBargain || this.bargainSwitch
          ? "当前状态为议价，确认是否发送议价"
          : `${message}？`
        }`,
        "提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        // 按单报价-发送
        if (val === 10)
          this.save(postData, true);
        // 同意
        if (val === 30)
          this.requestFunction("agree", { quotationId: this.value.quotationId });
        // 撤回
        if (val === 40)
          this.requestFunction("recall", { quotationId: this.value.quotationId });
        // 议价 
        if (val === 50)
          this.requestFunction("bargain", { ...postData, method: this.surcharge ? 'SURCHARGE' : 'STANDARD' });
        // 补充报价-发送，补充报价：被拒绝-发送
        if ([90, 100].includes(val))
          this.save(postData, true, true);
      });
    },
    //创建报价单
    handleSave (val) {
      // 补充费用
      let bargainFee = [];
      let bargainFlag = false; // 附加费金额是否为空
      if (this.computedDriver) {
        this.$refs.bargainRef.tableData.forEach((item) => {
          if ((item.money != 0 && !item.money && !item.title) || item.money === "" || (item.money && Number.isNaN(Number(item.money)))) {
            bargainFlag = true;
          }
          let obj = {
            money: item.money,
            type: item.type,
            remarks: item.remarks
          };
          if (
            !((["2", "3", "0"].includes(this.status) || (this.waybillQuoteBargain && this.surcharge)) && item.typeDisabled) &&
            !item.title
          ) {
            bargainFee.push(obj);
          }
        });
      }
      if (bargainFlag) {
        return this.$message.warning("补充费用不能为空");
      }
      // 付款方式
      let payTypeData = this.$refs.payType.tableData;
      // 请求参数
      let postData = {
        surchargeFees: bargainFee, // 补充费用
        arrivePayFee: payTypeData[0].arrivePayFee || 0, //货到付款
        prepayFee: payTypeData[0].prepayFee || 0, //预付款
        remarks: this.remarks,
        subjectId: this.value?.subjectId,
        quotationId: this.value?.quotationId
      };
      // 合单费用
      let transportCost = this.$refs.transportQuote.tableData[0];
      for (let key in transportCost) {
        postData[`${key}Fee`] = transportCost[key] || 0;
      }
      // 保存
      if (val === 20) {
        this.save(postData, false);
      }
      //发送
      if ([10, 90].includes(val)) {
        if (val === 90 &&
          postData.surchargeFees.length < 1 &&
          postData.arrivePayFee === Number(this.quoteDetail.arrivePayFee) &&
          postData.prepayFee === Number(this.quoteDetail.prepayFee)) {
          return this.$message.warning("您还未输入报价信息，请检查输入的值");
        }
        this.validateQuotation({ val, message: "确认发送", postData });
      }
      if ([50, 100].includes(val)) {
        this.confirmAction(val, "确认发送", postData);
      }
    },
    //保存
    async save (postData, flag, isAddSurcharge) {
      this.loading = true;
      let response;
      // isAddSurcharge true：补充报价 false：按单报价
      if (isAddSurcharge) {
        response = await quotation.addSurcharge({
          quotationId: this.value?.quotationId,
          ...postData,
          submit: flag
        })
          .catch(err => {
            this.loading = false
          });
      } else {
        response = this.value?.quotationId
          ? await quotation.updateQuotation(this.value?.quotationId, postData).catch(err => { this.loading = false })
          : await quotation.createQuotation(postData).catch(err => { this.loading = false });
      }
      let { code, data } = response;
      // flag true：发送 false：保存
      if (code === 0 && flag && !isAddSurcharge) {
        // 调用保存接口后，根据返回的quotationId调用发送接口
        this.requestFunction("sendQuotation", {
          quotationId: data.quotationId
        });
      } else {
        this.loading = false;
        this.handelClose();
      }
    },
    // 调用请求 requestType: ['sendQuotation': 发送, 'recall': 撤回, 'agree': 同意, 'bargain': 议价]
    async requestFunction (requestType, postData) {
      this.loading = true;
      let { code, message } = await quotation[requestType](postData)
        .catch(err => {
          this.loading = false;
        });
      this.$message[code === 0 ? "success" : "error"](message);
      this.loading = false;
      if (requestType === 'bargain' && this.bargainSwitch) {
        this.$router.back();
      } else {
        this.handelClose();
      }
    },
    // 关闭报价单
    async closeQuotation () {
      let { code } = await quotation.discard({ quotationId: this.value?.quotationId, surcharge: this.quoteDetail?.hasSurcharge });
      if (code === 0) {
        this.handelClose();
      }
    },
    // 跟踪信息
    async trackInformation () {
      if (this.value?.quotationId) {
        let { code, data } = await track.information(this.value?.quotationId, 'quotation');
        if (code === 0 && data.length) {
          data.map(item => {
            if (item.message.indexOf('，') != -1 && item.message.lastIndexOf('】')) {
              item.timestamp = item.message.slice(0, item.message.indexOf('，'))
              item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
              item.content = item.message.includes('】') ? item.message.slice(item.message.lastIndexOf('】') + 1) : item.message.slice(item.message.indexOf('，') + 1)
            }
          })
          this.track = data
          this.isTrack = true
        }
      }
    },
    // 关闭
    handelClose () {
      if (this.bargainSwitch) {
        this.bargainSwitch = false;
      } else {
        if (this.closeLabel === "返回") {
          this.$router.back();
        } else {
          window.close();
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.one-bill-wrap {
  height: calc(100vh - 80px);
  overflow-x: hidden;
  overflow-y: scroll;
}
.box-height {
  height: calc(100vh) !important;
}
.container {
  background: var(--prev-bg-white);
  margin: 0 auto;
  position: relative;
}
.w1200 {
  width: 1200px;
}
.mb20 {
  margin-bottom: 20px;
}
.fontSty1 {
  color: var(--prev-color-text-ashes);
  display: flex;
  justify-content: flex-end;
  height: 36px;
  line-height: 36px;
}
.fontSty2 {
  color: var(--prev-color-primary);
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}
.cost-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  span {
    color: var(--prev-border-color-grey);
    font-size: 12px;
  }
  .el-button {
    font-size: 16px;
  }
}
.ml8 {
  margin-left: 8px;
}
.totalSty {
  color: var(--prev-color-primary) !important;
}
.stampSty {
  width: 126px;
  height: 126px;
  position: absolute;
  left: 85%;
  top: 5%;
}
.remark {
  background: #fafafa;
  padding: 15px;
  margin-top: 25px;
  margin-bottom: 25px;
}
.wrap {
  word-break: break-all;
}
.mt25 {
  margin-top: 25px;
}
</style>
